package com.ubxtech.core.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 国密sm4加解密
 * @author Victor.Xiao
 * @since 2021-12-13 11:22
 **/
public class Sm4Util {

    /**
     *  SM4 加密
     * @author Victor.Xiao
     * @since 2021-12-13 11:24
     * @param sSrc sSrc
     * @param sKey sKey
     * @return java.lang.String
    */
    public static String encryptHex(String sSrc, String sKey){
        SymmetricCrypto sm4 = new SM4(Mode.ECB, Padding.ZeroPadding,sKey.getBytes(StandardCharsets.UTF_8));
        return sm4.encryptHex(sSrc, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * SM4 解密
     * @author Victor.Xiao
     * @since 2021-12-13 11:25
     * @param sSrc sSrc
     * @param sKey sKey
     * @return java.lang.String
    */
    public static String decryptStr(String sSrc, String sKey) {
        SymmetricCrypto sm4 = new SM4(Mode.ECB, Padding.ZeroPadding, sKey.getBytes(StandardCharsets.UTF_8));
        return sm4.decryptStr(sSrc, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * sdkv3 计算 sign
     * @author Victor.Xiao
     * @since 2021-12-13 11:30
     * @param params params
     * @param appSecret appSecret
     * @param values values
     * @return java.lang.String
    */
    public static String getSDKV3Sign(Map<String, Object> params, String appSecret, String... values) {
        if (params == null || StrUtil.isBlank(appSecret)) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        List<Map.Entry<String, Object>> mappingList = new ArrayList<>(params.entrySet());
        mappingList.sort(Comparator.comparing(mappingF -> mappingF.getKey().toLowerCase()));
        for (Map.Entry<String, Object> mapping : mappingList) {
            result.append(mapping.getValue() == null ? "" :
                    mapping.getValue());
        }
        for (String value : values) {
            result.append(value);
        }
        result.append(appSecret);
        return SmUtil.sm3(result.toString());
    }


    /**
     * v3 计算 sign
     * @author Victor.Xiao
     * @since 2021-12-13 11:30
     * @param params params
     * @param appSecret appSecret
     * @param values values
     * @return java.lang.String
     */
    public static String getSDKV3Sign(String projectId,String requestId,String robotId,String timestamp,String appSecret) {

        StringBuilder result = new StringBuilder();
        result.append(projectId);
        result.append(requestId);
        result.append(robotId);
        result.append(timestamp);
        result.append(appSecret);
        return SmUtil.sm3(result.toString());
    }

}
